package com.tsk.state.api.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import sun.net.www.http.HttpClient;

import java.net.URI;
import java.util.Map;

/** 用户控制器UserController
 * @author: 黄嘉振
 * @create: 2023/1/20 9:44
 * @description:
 **/
@RestController
@Validated
@Slf4j
public class LoginController {

    @GetMapping("/login")
    public void login(@RequestParam("code") String code) {
        System.out.println("code : " + code);
        // bbs
        String appid = "wx73c7b18b33b716a7";
        String secret = "daea37b131ffe176d9886149ec55fff1";
//        String appid = "wxd51e38915c9e417a";
//        String secret = "afad0f865a595edf5ddfbb71820102d4";
        RestTemplate restTemplate = new RestTemplate();
        // https://api.weixin.qq.com/sns/jscode2session
        // ?appid=<AppId>&secret=<AppSecret>&js_code=<code>&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "authorization_code");
        params.add("appid", appid);
        params.add("secret", secret);
        params.add("js_code", code);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.queryParams(params).build().encode().toUri();

        ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, String.class);
        String body = forEntity.getBody();
        System.out.println("body: " + body);
    }
}